package com.gouqi.mall.controller;

import com.gouqi.mall.domain.LoginInfo;
import com.gouqi.mall.domain.User;
import com.gouqi.mall.service.UserService;
import com.gouqi.mall.utils.CodeUtil;
import com.gouqi.mall.utils.MD5Util;
import com.gouqi.mall.utils.TokenUtils;
import com.gouqi.mall.utils.URLUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.UnsupportedEncodingException;
import java.util.Map;


/**
 * @author xiaofei
 * @time:2019-12-30
 */
@CrossOrigin
@Api(basePath = "/api/v1", value = "用户登录接口", description = "用户登录")
@Component
@RestController
@RequestMapping(value = "/login")
public class LoginController extends BaseController{

    //sessionKey
    private final String sessionKey = "RANDOMKEY";

    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;


    /**
     * 用户登录接口
     * @param info ：前端传进来的json格式数据
     * @return json:返回给前端的json信息
     * @throws UnsupportedEncodingException
     */
    @ResponseBody
    @RequestMapping(value = "/toLogin.do",method = RequestMethod.POST,produces = "application/json")
    @ApiOperation(value = "用户登录",notes = "一个用户登录进来，系统会自动为其创建一个token，作为唯一标识")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "byPhone",value = "登陆方式",required = true,dataType = "Boolean",defaultValue = "true"),
    })
    public String toLogin(@RequestBody @Valid LoginInfo info,Boolean byPhone) throws UnsupportedEncodingException {
        System.out.println("RequestBody中的用户信息："+info.getAccount());
        String pws = MD5Util.getMD5(info.getPassword());
        info.setPassword(pws);
        System.out.println("加密的密码："+info.getPassword());
        User user = userService.isHasUser(info.getAccount(), info.getPassword());
        JSONObject json = new JSONObject();
        if (user != null) {
            System.out.println("登錄用户昵称："+user.getNickName());
            System.out.println("登录用户手机："+user.getPhone());
            System.out.println("登录用户id："+user.getUserId());
            //创建token
            String token = TokenUtils.createToken(user);
            json.put("status",200);
            json.put("message","登陆成功");
            json.put("result","success");
            json.put("token",token);
            json.put("userId",user.getUserId());
        } else {
            json.put("status",404);
            json.put("message","没有该用户，请输入正确的用户名密码");
            json.put("result","failed");
            json.put("token","");
            json.put("userid","");
        }
        return json.toString();
    }

    /**
     * 用户登陆接口:
     *        用手机号，密码和验证码登录
     * @param info 登录信息，放在请求体中
     * @param request
     * @param byPhone
     * @return json
     * @throws UnsupportedEncodingException
     */
    @ResponseBody
    @RequestMapping(value = "/actionLogin.do",method = RequestMethod.POST,produces = "application/json")
    @ApiOperation(value = "用户登录",notes = "用户用手机号登录进来，系统会自动为其创建一个token，作为唯一标识")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "byPhone",value = "登陆方式",required = true,dataType = "Boolean",defaultValue = "true"),
    })
    public String toLoginByPhone(@RequestBody @Valid LoginInfo info,HttpServletRequest request,Boolean byPhone) throws UnsupportedEncodingException {
        JSONObject json = new JSONObject();
        HttpSession session = request.getSession();
        String randomCode = session.getAttribute("RANDOMKEY").toString();
        System.out.println("填入的验证码："+randomCode);
        System.out.println("RequestBody中的用户信息："+info.getAccount());
        String pws = MD5Util.getMD5(info.getPassword());
        info.setPassword(pws);
        System.out.println("加密的密码："+info.getPassword());
        if (randomCode.equals(info.getCode())){
            User u = userService.userIsExist(info.getPhone(),info.getPassword());
            if (u != null) {
                //创建token
                String token = TokenUtils.createToken(u);
                json.put("status",200);
                json.put("message","登陆成功");
                json.put("result","success");
                json.put("token",token);
                json.put("userId",u.getUserId());
            } else {
                json.put("status",404);
                json.put("message","没有该用户，请输入正确的用户名密码");
                json.put("result","failed");
                json.put("token","");
                json.put("userid","");
            }
        } else {
            json.put("status",101);
            json.put("message","验证码错误，请重新填写验证码！");
        }
        return json.toString();
    }

}
